﻿

using Digitalmes.Attributes;
using Elsa.Server.Api.Endpoints.Activities;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;


namespace Digitalmes.Extensions
{
   public static class MediatrExtension
    {
        // 扩展方法：注册WTM专属MediatR
        public static void AddWtmMediatR(this IServiceCollection services)
        {

            // 1. 创建独立的服务容器
            // var wtmContainer = new ServiceCollection();

            //// 2. 获取WTM专属程序集（排除Elsa.Core）
            var wtmAssemblies = AppDomain.CurrentDomain.GetAssemblies()
                .Where(x => x.FullName.Contains("Digitalmes") &&
                       !x.FullName.Contains("Elsa.Core"))
                .ToList();

            services.AddDigitalMesMediatr(wtmAssemblies);

            // 3. 使用您提供的注册方法（修改版）
            // wtmContainer.AddDigitalMesMediatR(wtmAssemblies);

            // 4. 构建独立的服务提供者
            //var wtmProvider = wtmContainer.BuildServiceProvider();

            // 5. 将Mediator实例注册为全局单例
            // services.AddSingleton<IMediator>(wtmProvider.GetRequiredService<IMediator>());

            // 6. 注册包装器（可选，推荐）
            //services.AddSingleton<WtmMediator>();
        }





         static void AddDigitalMesMediatr(this IServiceCollection container,  List<Assembly> assemblies)
        {                          
            var noticetypes = assemblies
                 .SelectMany(a => a.GetTypes())
                 .Where(t => !t.IsAbstract &&  t.GetInterfaces().Any(i =>
                       i.IsGenericType &&                   
                       i.GetGenericTypeDefinition() == typeof(INotificationHandler<>)))
                      .ToList();
            foreach (var noticeType in noticetypes)
            {
                //获取接口泛型类型
                var generictype = noticeType.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(INotificationHandler<>));
                //获取定义接口类型
               // var genericInterface = typeof(INotificationHandler<>).MakeGenericType(generictype);
                container.AddTransient(generictype, noticeType);
            }

            // 1. 注册所有管道行为

            // 筛选出实现了IPipelineBehavior<,>接口的类型
            var behaviorTypes = assemblies
                 .SelectMany(a => a.GetTypes())
                .Where(type =>
                type.IsClass && !type.IsAbstract && // 只考虑具体类
                type.GetInterfaces().Any(i =>
                    i.IsGenericType &&
                    i.GetGenericTypeDefinition() == typeof(IPipelineBehavior<,>)) // 检查是否实现了目标接口
            ).ToList();

            // 按Order特性排序
            var orderedBehaviors = behaviorTypes
                .Select(type => new
                {
                    Type = type,
                    // 获取Order特性，如果没有则默认为int.MaxValue（排在最后）
                    Order = type.GetCustomAttribute<OrderAttribute>()?.Order ?? int.MaxValue
                })
                .OrderBy(item => item.Order) // 按Order值升序排序
                .Select(item => item.Type)
                .ToList();

           

            foreach (var behaviorType in orderedBehaviors)
            {              
                ////获取接口泛型类型
                //var generictype = behaviorType.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IPipelineBehavior<,>));
                ////获取定义接口类型
                //var genericInterface = typeof(IPipelineBehavior<,>).MakeGenericType(generictype);

                container.AddTransient(typeof(IPipelineBehavior<,>), behaviorType);
            }


            var requesttypes = assemblies
               .SelectMany(a => a.GetTypes())
               .Where(t => !t.IsAbstract && t.GetInterfaces().Any(i =>
                     i.IsGenericType &&
                     i.GetGenericTypeDefinition() == typeof(IRequestHandler<,>)))
                    .ToList();

        
            foreach (var requestType in requesttypes)
            {

                //获取接口泛型类型
                var generictype = requestType.GetInterfaces().FirstOrDefault(
                                 i => i.IsGenericType &&
                                 i.GetGenericTypeDefinition() == typeof(IRequestHandler<,>));
                
                container.AddTransient(generictype, requestType);
            }



           

        }
    }
}
